package com.woniu.goods.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.woniu.goods.domain.Manager;
import com.woniu.goods.service.IUserService;
import com.woniu.goods.service.UserServiceImpl;

@WebServlet("/login")
public class LoginAction extends HttpServlet {
	IUserService us = new UserServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//接收用户名和密码
		String name = req.getParameter("username");
		String pass = req.getParameter("password");
		
		//接收是否记住密码的标识
		String flag = req.getParameter("flag");
		
		Manager manager = us.findManagerByNameAndPass(name, pass);
		if (manager != null) {
			//登陆成功  把用户信息存储到session
			req.getSession().setAttribute("userInfo", manager);
			
			//操作是否记住密码
			if ("1".equals(flag)) {
				Cookie cookie = new Cookie("managerInfo", manager.getUsername()+":"+manager.getPassword());
				cookie.setMaxAge(60*60*24*14);
				cookie.setPath("/");
				resp.addCookie(cookie);
			}
			
			//转向查询商品数据
			resp.sendRedirect(req.getContextPath()+"/per/list");
		}else {
			//登陆失败
			req.setAttribute("info", "您的用户名或者密码错误,请重新登陆!");
			req.getRequestDispatcher("/jsp/login.jsp").forward(req, resp);
		}
		
	}
	
}
